<script setup>
import { ref } from 'vue'
import { getCategoryApi } from '@/api/category'
import { createNovelApi } from '@/api/novel'
import router from '@/router'
// 表单绑定
const Ruleform = ref({
  title: '',
  introduction: '',
  categoryName: ''
})
const form = ref()
// 规则
const rule = ref({
  title: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '小说名字长度为2到20', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '小说介绍大于2个字符', trigger: 'blur' }
  ]
})
// 添加小说
const createNovel = async () => {
  await form.value.validate()
  const res = await createNovelApi(Ruleform.value)
  if (res.status === 200) {
    ElMessage.success('添加成功')
    router.push('/')
  }
  // console.log(res.status)
}

// 获取分类
const categoryList = ref([])
const getCategory = async () => {
  const res = await getCategoryApi()
  // console.log(res.data.data)
  categoryList.value = res.data.data
}
getCategory()

const cancel = () => {
  router.push('/')
}
</script>
<template>
  <el-row :gutter="20">
    <el-col :span="12" :offset="6">
      <el-form
        :model="Ruleform"
        ref="form"
        :rules="rule"
        label-width="auto"
        style="max-width: 600px"
        class="el-form"
      >
        <el-form-item> 创建新书 </el-form-item>
        <el-form-item label="请输入书名" prop="title">
          <el-input v-model="Ruleform.title" />
        </el-form-item>
        <el-form-item label="请输入简介" prop="introduction">
          <el-input v-model="Ruleform.introduction" type="textarea" />
        </el-form-item>
        <el-form-item label="书籍分类">
          <el-select
            v-model="Ruleform.categoryName"
            placeholder="请选择你的书籍类型"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createNovel">创建</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<style>
.el-form {
  margin-top: 100px;
}
</style>
